package com.pan;

import com.pan.entity.PosNameMapper;
import com.pan.io.ReadCSV;
import com.pan.mapping.EntityToSQL;
import com.pan.mapping.LineToObject;
import com.pan.utils.ToStringUtils;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

public class MyCSVTools<T> {
    private ReadCSV readCSV;
    private LineToObject<T> lineToObject;
    private String tableName;
    private boolean hasTitle;
    private EntityToSQL<T> entityToSQL;


    public MyCSVTools(File csvFile, String limiter, Class<T> objClass, List<PosNameMapper> posNameMapperList,String tableName,boolean hasTitle) {
        readCSV = new ReadCSV(csvFile,limiter);
        this.entityToSQL = new EntityToSQL<>(objClass);
        lineToObject = new LineToObject<T>(objClass,posNameMapperList);
        this.tableName = tableName;
        this.hasTitle = hasTitle;
    }
    public MyCSVTools(File csvFile, Class<T> objClass, List<PosNameMapper> posNameMapperList) {
        this(csvFile,",",objClass,posNameMapperList,
                objClass.getName().split("\\.")[objClass.getName().split("\\.").length-1],
                true);
    }


    public void toInsertSQL(File fileSql){
        if (!readCSV.hasNextLine()) throw new RuntimeException("csv文件为空");
        if (hasTitle){
            readCSV.nextLine();
        }
        FileWriter fileWriter;
        try {
            if (!fileSql.exists())fileSql.createNewFile();
            fileWriter = new FileWriter(fileSql,true);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        int i = 0;
        String insertSql ="";
        while (readCSV.hasNextLine()){
            String[] arr = readCSV.nextLine();
            T object = lineToObject.arrToObject(arr);
            insertSql += entityToSQL.getInsert(object, tableName)+"\n";
            i++;
            if (i==100){
                try {
                    fileWriter.write(insertSql);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                i = 0;
                insertSql = "";
            }
        }

        try {
            fileWriter.write(insertSql);
            fileWriter.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
